package com.gaojinqi.controller;

import com.gaojinqi.dto.OrderDTO;
import com.gaojinqi.enums.ResultEnum;
import com.gaojinqi.exception.SellException;
import com.gaojinqi.service.OrderService;
import com.gaojinqi.service.PayService;
import com.lly835.bestpay.model.PayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;
import java.util.Optional;

/**
 * @author gaojinqi
 * @date 2019/5/7 2:10
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    private final OrderService orderService;

    private final PayService payService;

    @Autowired
    public PayController(OrderService orderService, PayService payService) {
        this.orderService = orderService;
        this.payService = payService;
    }

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String, Object> map) {
        // 1.查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        Optional.ofNullable(orderDTO).orElseThrow(() -> new SellException(ResultEnum.ORDER_NOT_EXIST));
        // 2.发起支付
        PayResponse payResponse = payService.create(orderDTO);
        map.put("payResponse", payResponse);

        return new ModelAndView("pay/create");
    }

    /**
     * 微信异步通知
     *
     * @param notifyData
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        PayResponse payResponse = payService.notify(notifyData);
        // 返回微信处理结果
        return new ModelAndView("pay/success");
    }
}
